<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>
    <el-form label-width="80px" @submit.native.prevent>
      <el-form-item label="文章标题">
        <el-input v-model="model.name" placeholder="请输入文章标题"></el-input>
      </el-form-item>

      <el-form-item label="所属分类">
        <el-select
          v-model="model.categories"
          placeholder="请选择"
          multiple
          filterable
        >
          <el-option
            v-for="item in parents"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="文章详情">
        <vue-editor
          useCustomImageHandler
          @image-added="handleImageAdded"
          v-model="model.body"
        ></vue-editor>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save()">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { VueEditor } from "vue2-editor";
export default {
  data() {
    return {
      model: {
        name: "",
        categories: "",
        body: ""
      },
      parents: []
    };
  },
  props: {
    id: { type: String }
  },
  components: {
    VueEditor
  },
  methods: {
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);

      this.$http.post("upload", formData).then(res => {
        Editor.insertEmbed(cursorLocation, "image", res.data.url);
        resetUploader();
      });
    },
    handparents() {
      this.$http.get("/rest/categories").then(res => {
        this.parents = res.data;
      });
    },
    save() {
      if (this.id) {
        this.$http.put(`/rest/articles/${this.id}`, this.model).then(() => {
          this.$message({
            message: "修改成功",
            type: "success"
          });
        });
        this.$router.push("/articles/list");
      } else {
        this.$http.post("/rest/articles", this.model).then(() => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
        });
        this.$router.push("/articles/list");
      }
    },

    fetch() {
      this.$http.get(`/rest/articles/${this.id}`).then(res => {
        // this.model=res.data
        this.model = res.data;
      });
    }
  },

  created() {
    this.handparents();
    this.id && this.fetch();
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
